package main

import (
	"../tools"
	"fmt"
	"github.com/zouyx/agollo"
	"net/http"
	"strings"
	"time"
)

var shellHelper tools.ShellHelper
var logHelper tools.LogHelper

func main() {

	err := agollo.Start()
	if err != nil {
		logHelper.LogError(fmt.Sprintf("启动apollo失败"), err)
		return
	}

	str := agollo.GetStringValue("CheckServerConfig", "")
	configMap := make(map[string]interface{}, 10)
	configMap["serverConfig"] = str
	configMap["commandTemplate"] = agollo.GetStringValue("CheckCommandTemplate", "ps -ef|grep %s")
	configMap["excludeString"] = agollo.GetStringValue("CheckExcludeString", "grep")
	configMap["ipPrefixString"] = agollo.GetStringValue("LocalIpPrefix", "192.168.0.")
	configMap["logpath"] = agollo.GetStringValue("LogPath", "daemon-%s.log")
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "\t", configMap)
	objchan := agollo.ListenChangeEvent()
	for {
		if apolloevent, ok := <-objchan; ok {
			if apolloevent.Changes != nil && len(apolloevent.Changes) > 0 {
				for key, val := range apolloevent.Changes {
					fmt.Println(fmt.Sprintf("key=%s,changetype=%v,,oldvalue=%s,newvalue=%s", key, val.ChangeType, val.OldValue, val.NewValue))
				}
			}
			continue
		}
		time.Sleep(5 * time.Second)
	}

	//testRabbitMQ()

	logHelper = tools.NewLogHelper("%s.log", true, "守护进程")
	logHelper.LogInfo("aaaaaaaaaaaa")
	time.Sleep(10 * time.Second)
}

func handlerPort(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "ok")
}

func testRabbitMQ() {
	var rabbitmqHelper tools.RabbitMqHelper
	rabbitmqHelper.ConnectionString = "amqp://devops:devops@59.110.164.116:5672//framework"
	rabbitmqHelper.ExchangeType = "topic"
	rabbitmqHelper.Exchange = "user_center_ex_1"
	rabbitmqHelper.DeliveryMode = 2
	rabbitmqHelper.InitMQConnection()

	msginfo := "test message"
	ret := rabbitmqHelper.SendMQMessageWithRoutekey([]byte(msginfo), "woman")
	fmt.Println(fmt.Sprintf("MQ发送完成：%v", ret))
}

func testCommand() {
	cmdstr := "-ef|grep TestS1"
	cmdstr = "|findstr /i 'explorer.exe'"
	arrParam := []string{cmdstr}
	fmt.Println(arrParam)
	//arr, _ := shellHelper.ExecCommandWithLineOutput("/usr/bin/ps", arrParam)
	str, _ := shellHelper.ExecCommandWithOutput("ps -ef|grep TestS1")
	fmt.Println("执行结束---->")
	fmt.Println(str)
	fmt.Println("----------------------")

	arrResult := strings.Split(str, " ")
	fmt.Println(arrResult)
}
